package org.springframework.security.web.context;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.function.SingletonSupplier;

import java.util.function.Supplier;

/**
 * @author Dillon
 * @date 2024/7/10
 * @slogan 致敬大师 致敬未来的你
 * @desc 登录缓存对象持久化接口 ，用于将缓存持久化至特定地方
 */
public interface SecurityContextRepository {

	/**
	 * 从持久化位置将缓存加入内存
	 *
	 * @param requestResponseHolder 原始请求响应持有类
	 * @return 缓存对象
	 */
	@Deprecated
	SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder);

	/**
	 * 根据请求对象从缓存中获取延时缓存对象
	 *
	 * @param request 请求对象
	 * @return 延时缓存
	 */
	default DeferredSecurityContext loadDeferredContext(HttpServletRequest request) {
		Supplier<SecurityContext> supplier = () -> loadContext(new HttpRequestResponseHolder(request, null));
		return new SupplierDeferredSecurityContext(SingletonSupplier.of(supplier),
				SecurityContextHolder.getContextHolderStrategy());
	}

	/**
	 * 将缓存对象放入缓存中
	 *
	 * @param context  缓存对象
	 * @param request  请求对象
	 * @param response 响应对象
	 */
	void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response);

	/**
	 * 判断缓存中是否包含当前请求的缓存
	 *
	 * @param request 请求对象
	 * @return 是否包含已存储对象
	 */
	boolean containsContext(HttpServletRequest request);

}
